package com.odm.communitymanage.ui.activity

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jeremyliao.liveeventbus.LiveEventBus
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.MyActivityData
import com.odm.communitymanage.ui.CMViewPagerAdapter
import com.odm.communitymanage.ui.activity.states.LatestActivitiesFragment
import com.odm.communitymanage.ui.activity.states.OngoingActivitiesFragment
import com.odm.communitymanage.ui.activity.states.OverActivitiesFragment
import com.odm.communitymanage.ui.notifications.NoticeDetailFragment
import com.odm.communitymanage.util.DrawableUtil
import com.zhengsr.tablib.view.adapter.TabFlowAdapter
import com.zhengsr.tablib.view.flow.TabFlowLayout
import kotlinx.android.synthetic.main.frgment_activities.*
import me.yokeyword.fragmentation.ISupportFragment

/**
 * @description: 活动列表 页面
 * @author: ODM
 * @date: 2020/4/20
 */
class ActivityListFragment :  BaseMVVMFragment() {

    var rvAdapter : ActivitiesAdapter ?= null

    private var viewModel : ActivitiesViewModel ?= null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewModel = ViewModelProviders.of(this).get(ActivitiesViewModel::class.java)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
        //可见时，刷新首页列表
        refreshActivityList(viewModel?.selectedTabIndex)
    }

    override fun initViews() {
//        initTabLayout()
//
//        initActivityRecyclerView()

        initActivitiesViewPager()

        initTabFlowLayout()

        initSearchEditText()

        btnBackActivities?.setOnClickListener {
            pop()
        }

        tvPostActivities?.setOnClickListener {
            start(PostActivityFragment())
        }
    }

    /**
     * 初始化搜索框的搜索触发点击事件
     */
    private fun initSearchEditText(){
        //
        etSearchActivity.setOnEditorActionListener { v, actionId, event ->
            return@setOnEditorActionListener when (actionId) {

                EditorInfo.IME_ACTION_SEARCH -> {
                    searchActivity()
                    true
                }
                else -> false
            }

        }
        //搜索框的右侧图片点击事件
        val drawRightClick : DrawableUtil = DrawableUtil(etSearchActivity , object : DrawableUtil.OnDrawableListener{
            override fun onLeft(v: View?, left: Drawable?) {
            }
            override fun onRight(v: View?, right: Drawable?) {
                searchActivity()
            }
        })
    }

    private fun searchActivity(){
        val s = etSearchActivity?.text?.toString()
        if(s != ""){
            hideSoftInput()
            viewModel?.searchActivityList(etSearchActivity?.text?.toString() ?: "")
        }else {
            ToastUtils.showShort("搜索内容不可为空")
        }
    }

    private fun  initActivityRecyclerView(){
        rvActivities?.layoutManager = LinearLayoutManager(requireContext())
        rvAdapter = ActivitiesAdapter(mutableListOf())
        rvActivities?.adapter  = rvAdapter
        rvAdapter?.animationEnable = true
        rvAdapter?.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
        //设置空布局
        rvAdapter?.setEmptyView(R.layout.layout_empty_list)
        //item 的点击事件
        rvAdapter?.setOnItemClickListener{ adapter, view, position ->
            //传递数据和事件
            LiveEventBus.get(Constants.EVENT_ACTIVITY_DETAIL)
                .post(rvAdapter?.data?.get(position))
            start(ActivityDetailFragment())
        }
    }


    private fun initTabLayout(){
        //TabLayout点击事件
        tabActivities?.configTabLayoutConfig {
            //选中项的view的回调
            onSelectViewChange = { fromView, selectViewList, reselect ->
                val toView = selectViewList.first()
                if (reselect) {
                    //重复选择
                }
            }
            //选中项index的回调事件
            onSelectIndexChange = { fromIndex, selectIndexList, reselect ->
                //toIndex 为 选中 Index
                val toIndex = selectIndexList.first()
                //更新tabIndex选中回调
                viewModel?.selectedTabIndex  = toIndex
                refreshActivityList(toIndex)
            }
        }
    }


    private fun initActivitiesViewPager(){
        vpActivities.adapter = CMViewPagerAdapter(childFragmentManager,
                                                  mutableListOf( LatestActivitiesFragment(),OngoingActivitiesFragment(),OverActivitiesFragment() ))
//        vpActivities.offscreenPageLimit = 2
    }

    private fun initTabFlowLayout(){
        val tabTitles: List<String> = mutableListOf(getString(R.string.lastest_posted),getString(R.string.ongoing),getString(R.string.over))
        val flowLayout: TabFlowLayout = tfLActivities
        tfLActivities
            .setTextId(R.id.item_text)
            .setSelectedColor(ColorUtils.getColor(R.color.tab_selected))
            .setUnSelectedColor(ColorUtils.getColor(R.color.tab_unselected))
            .setViewPager(vpActivities)
        //设置数据，这里以 setAdapter 的形式
        flowLayout.adapter = object : TabFlowAdapter<String?>(R.layout.item_tab_text, tabTitles) {
            override fun onItemSelectState(view: View?, isSelected: Boolean) {
                super.onItemSelectState(view, isSelected)
                //选中时，可以改变不同颜色，如果你的background 为 selector，可以不写这个
            }

            override fun onItemClick(view: View?, data: String?, position: Int) {
                super.onItemClick(view, data, position)
                //viewPager换页
                vpActivities.currentItem = position
            }

            override fun bindView(view: View?, data: String?, position: Int) {
                setText(view, R.id.item_text, data).setTextColor(view, R.id.item_text, resources.getColor(R.color.tab_unselected))
            }
        }
    }

    override fun initViewModelObserve() {
/*        //观察请求返回的列表
        viewModel?.activityList?.observe(this ,object : Observer<List<MyActivityData>>{
            override fun onChanged(t: List<MyActivityData>?) {
                //加载列表
                rvAdapter?.setNewData(t?.toMutableList())
            }
        })*/
    }



    public fun startDetailFragment(){
        start(ActivityDetailFragment(), ISupportFragment.SINGLETASK)
    }

    private fun refreshActivityList(index : Int ?){
        when(index){
            0 -> {
                viewModel?.getNewestActivityList()
            }
            1 -> {
                viewModel?.getOngoingList()
            }
            2 -> {
                viewModel?.getOverList()
            }
            else -> {}
        }
    }


    override fun getLayoutId(): Int {
        return R.layout.frgment_activities
    }
}